$(function () {
    var customerSource = {
        grade: ["A", "B", "C", "D"],
        items: {},
        houseFlag: true,
        customerFlag: true,
        currentCustomerSource: {},
        typeArray: {},
        isUpdateOrApproval: null,
        checkUser: [],
        currentVillageName: null,
        currentHid: null,
        currentCid: null
    };

    customerSource.items.name = com.focusPage("#name");
    customerSource.items.gender = com.focusPage("#gender");
    customerSource.items.phone = com.focusPage("#phone");
    customerSource.items.purpose = com.focusPage("#purpose");
    customerSource.items.intention = com.focusPage("#intention");
    customerSource.items.price = com.focusPage("#price");
    customerSource.items.grade = com.focusPage("#grade");
    customerSource.items.comment = com.focusPage("#comment");

    customerSource.items.villageNo = com.focusPage("#villageNo");
    customerSource.items.houseNumber = com.focusPage("#houseNumber");
    customerSource.items.buildArea = com.focusPage("#buildArea");
    customerSource.items.houseType = com.focusPage("#houseType");
    customerSource.items.salesmanType = com.focusPage("#salesmanType");
    customerSource.items.orderType = com.focusPage("#orderType");
    customerSource.items.resourceType = com.focusPage("#resourceType");
    customerSource.items.approveComment = com.focusPage("#approveComment");
    customerSource.items.checkApproveMan = com.focusPage("#checkApproveMan");

    customerSource.items.built = com.focusPage("#built");
    customerSource.items.unit = com.focusPage("#unit");
    customerSource.items.floor = com.focusPage("#floor");
    customerSource.items.door = com.focusPage("#door");
    customerSource.items.builtrule = com.focusPage("#builtrule");
    customerSource.items.unitrule = com.focusPage("#unitrule");
    customerSource.items.floorrule = com.focusPage("#floorrule");
    customerSource.items.doorrule = com.focusPage("#doorrule");
    customerSource.items.ruleTwo = com.focusPage("#ruleTwo");

    customerSource.items.designer = com.focusPage("#designer");

    customerSource.items.rule = com.focusPage("#rule");

    customerSource.items.grade.bindData(customerSource.grade);
    customerSource.items.gender.switchBtn("gender");

    com.post(api.ds.building, {}, function (res) {
        customerSource.items.builtrule.bindData(res.buildrule, "key", "value");
        customerSource.items.unitrule.bindData(res.buildrule, "key", "value");
        customerSource.items.floorrule.bindData(res.buildrule, "key", "value");
        customerSource.items.doorrule.bindData(res.buildrule, "key", "value");
    }, null, false);

    com.initChosen('villageNo', api.data.queryVillageForNameByPinyin, "pinyinName", {}, "autoFillKeyValue", "key", "value");
    com.initChosen('designer', api.personel.queryUserByPinyin, "pinyinName", {"user.status": 0}, 'autoFillKeyValue', 'key', 'value');

    customerSource.items.villageNo.on('change', function () {
        com.post(api.data.queryVillageById, {"village.no": customerSource.items.villageNo.val()}, function (res) {
            customerSource.items.rule.html("推荐楼牌号规则：" + res.village.rule);
        }, null, false);
    });

    customerSource.updateAndApprovalBtn =  com.focusPage("#updateAndApprovalBtn").on("click", customerApproval);
    customerSource.saveDesignerBtn =  com.focusPage("#saveDesignerBtn").on("click", updateDesigner);

    com.focusPage("#sustomersource").on("hidden.bs.modal", function(){
        customerSource.isUpdateOrApproval = null;
        com.clearValidator("#villageNo", true);
        com.clearValidator("#houseNumber", true);
        com.clearValidator("#name", true);
        com.focusPage("#rule").html("");
        com.focusPage("#houseNumber").removeAttr("data-content");
        com.focusPage("#name").removeAttr("data-content");
        customerSource.checkUser = [];
        customerSource.currentHid = null;
        customerSource.currentCid = null;
    });

    com.post(api.ds.decoration, {}, function (res) {
        customerSource.items.salesmanType.bindData(res.salesmanType, 'key', 'value');
        customerSource.items.orderType.bindData(res.type, 'key', 'value');
        customerSource.items.resourceType.bindData(res.status, 'key', 'value');
    }, null, false);

    com.post(api.ds.building, {}, function (res) {
        customerSource.typeArray = res.houseType;
    }, null, false);

    var displayFunc = (function () {
        var renderList = function (tableId, listData) {
            var $tableWrap = com.focusPage('#' + tableId);
            var $ul = $('<ul></ul>').addClass('item-list fl-table-list ui-sortable');
            if (listData && listData.length) {
                $.each(listData, function (i, v) {
                    var $liLine = creatLine(v);
                    $liLine.appendTo($ul);
                });
                $ul.appendTo($tableWrap);
            }
        };

        var creatLine = function (v) {
            var $liLine = $('<li></li>').addClass('item-orange clearfix ');
            var $h3 = $('<h3></h3>').addClass('oid').append($('<small></small>').addClass('blue').html(v.name));
            var $ulProperty = $('<ul></ul>').addClass('list-unstyled fl-inline-list clearfix');
            var $divBtnWrap = $('<div></div>').addClass('pull-right action-buttons');

            var $btnView = $("<a></a>").addClass("btn btn-minier btn-yellow").html("编辑");
            var $btnDesigner = $("<a></a>").addClass("btn btn-minier btn-success").html("编辑设计师");
            var $btnApproval = $("<a></a>").addClass("btn btn-minier btn-warning").html("转装修单");
            var $release = $("<a></a>").addClass("btn btn-minier btn-pink").html("释放");
            var $record = $("<a></a>").addClass("btn btn-minier btn-danger").html("记录");

            var propertyArr = [
                ["客户电话: ", v.phone, "grey"],
                ["性别: ", v.gender, "grey"],
                ["目的: ", v.purpose, "grey"],
                ["意向: ", v.intention, "grey"],
                ["需求价格: ", v.price, "blue"],
                ["客户等级: ", v.grade, "grey"],
                ["创建人: ", v.creater.currentName, "grey"],
                ["创建时间: ", v.createTime, "green"],
                ["归属人: ", v.belonger.currentName, "grey"],
                ["归属部门: ", v.department.name, "grey"],
                ["归属分区: ", v.region.name, "grey"],
                ["归属设计师: ", com.checkNull(v.designer.currentName,'无'), "grey"],
                ["楼盘名: ",com.checkNull(v.village.name,'无'), "grey"],
                ["楼牌号: ", v.houseNumber, "blue"],
                ["建筑面积: ", v.buildArea, "blue"],
                ["备注: ", com.checkNull(v.comment, '无'), "grey"]
            ];

            $.each(propertyArr, function (index, value) {
                var $liProperty = $('<li></li>');
                $('<strong></strong>').html(value[0]).appendTo($liProperty);
                $('<b></b>').html(value[1]).addClass(value[2] ? value[2] : "").appendTo($liProperty);
                $liProperty.appendTo($ulProperty);
            });

            if(v.status == 0){
                $divBtnWrap.append($btnView).append($btnDesigner).append($btnApproval).append($release);
            }

            $divBtnWrap.append($record);

            $divBtnWrap.appendTo($h3);

            $liLine.append($h3).append($ulProperty);

            //编辑
            $btnView.click(function () {
                customerSource.currentCustomerSource = v;
                com.focusPage("#sustomersourceDialog").html("编辑客源");
                customerSource.isUpdateOrApproval = "update";
                isOtherCustomerSource(false);
                editcustomerOrigin(v);
            });

            $record.click(function () {
                record(v.csid);
            });

            $release.click(function () {
                if(v.belonger.userId == null){
                    com.showAlert(com.warning, "无归属人信息!");
                    return;
                }
                release(v.csid);
            });

            //编辑设计师
            $btnDesigner.click(function () {
                customerSource.currentCustomerSource = v;
                if(v.designer != null && v.designer.uid != null){
                    com.updateChosen("designer", v.designer.userId, v.designer.currentName);
                }else{
                    com.updateChosen("designer", "", "");
                }
                com.clearValidator("#designer", true);
                com.focusPage("#updateDesigner").modal("show");
            });

            //转装修单提交审批
            $btnApproval.click(function () {
                initqueryApprovalUserForCheckbox("approveMan", 14, "checkApproveMan");
                customerSource.currentCustomerSource = v;
                com.focusPage("#sustomersourceDialog").html("提交审批");
                customerSource.isUpdateOrApproval = "approval";
                isOtherCustomerSource(true);
                editcustomerOrigin(v);
            });

            return $liLine;
        };
        return {
            init: function (tableId, listData) {
                com.focusPage('#' + tableId).html(null);
                renderList(tableId, listData);
            },
            drawLine: function (v) {
                return creatLine(v);
            }
        };
    })();

    var searcher = new Searcher();

    searcher.init(["customerSourcePhone"], "condList", api.customer.pageCustomerOrigin, function (data) {
        displayFunc.init("resultList", data);
    }, "pagenation", "customerOriginPostData", null, false, null, null);

    function editcustomerOrigin(d) {
        com.cleanItems(customerSource.items);
        com.clearValidator();

        customerSource.items.name.val(d.name);
        customerSource.items.gender.val(d.gender);
        customerSource.items.phone.val(d.phone);
        customerSource.items.purpose.val(d.purpose);
        customerSource.items.intention.val(d.intention);
        customerSource.items.price.val(d.price);
        customerSource.items.grade.val(d.grade);
        customerSource.items.comment.val(d.comment);
        customerSource.items.houseNumber.val(d.houseNumber);
        customerSource.items.buildArea.val(d.buildArea);

        if(d.gender == "女"){
            customerSource.items.gender.prop("checked", true);
        }

        if(d.gender == "男"){
            customerSource.items.gender.prop("checked", false);
        }

        if(d.village != null && d.village.name != null){
            com.updateChosen('villageNo', d.village.no, d.village.name + "-" + d.village.cityProper.name);
            customerSource.currentVillageName = d.village.name;
        }else{
            com.updateChosen('villageNo', "", "");
        }
        com.focusPage("#sustomersource").modal("show");
    }

    //提交审批
    function customerApproval(){
        if (com.validate("sustomersource")) {
            return;
        }

        if(customerSource.isUpdateOrApproval == "update"){
            var customerId = null;
            var houseId = null;
            var houseName = null;

            var options = {
                "customerOrigin.csid": customerSource.currentCustomerSource.csid,
                "customerOrigin.name": customerSource.items.name.val(),
                "customerOrigin.gender": com.genderType[customerSource.items.gender.prop("checked")],
                "customerOrigin.phone": customerSource.items.phone.val(),
                "customerOrigin.purpose": customerSource.items.purpose.val(),
                "customerOrigin.intention": customerSource.items.intention.val(),
                "customerOrigin.price": customerSource.items.price.val(),
                "customerOrigin.grade": customerSource.items.grade.val(),
                "customerOrigin.comment": customerSource.items.comment.val(),
                "customerOrigin.village.no": customerSource.items.villageNo.val(),
                "customerOrigin.houseNumber": customerSource.items.houseNumber.val(),
                "customerOrigin.buildArea": customerSource.items.buildArea.val()
            };

            com.post(api.customer.updateCustomerOrigin, options, function (res) {
                searcher.doSearch();
                com.showAlert(com.info, '修改成功');
                com.focusPage("#sustomersource").modal("hide");
            });
        }else if(customerSource.isUpdateOrApproval == "approval"){
            //审批创建装修单
            if(customerSource.checkUser.length == 0){
                com.showAlert(com.warning, "请选择审批人!");
                return;
            }

            if(customerSource.currentCustomerSource.belonger.userId == null){
                com.showAlert(com.warning, "请确认业务员信息!");
                return;
            }

            if(customerSource.items.villageNo.val() == ""){
                com.showTips(com.focusPage("#villageNo"), "内容不能为空", true);
                return;
            }else{
                com.clearValidator("#villageNo", true);
            }

            if(customerSource.items.houseNumber.val() == ""){
                com.showTips(com.focusPage("#houseNumber"), "内容不能为空", true);
                return;
            }else{
                com.clearValidator("#houseNumber", true);
            }

            bootbox.confirm("确认要提交审批吗?", function(res) {
                if(res){
                    //这里判断当前操作人是否是设计师，如果是可以提交审批
                    if (params.userInfo.user.uid == customerSource.currentCustomerSource.designer.uid) {
                        if(customerSource.currentHid == null){
                            com.showAlert(com.warning, "请绑定房产!");
                            return;
                        }

                        if(customerSource.currentCid == null){
                            com.showAlert(com.warning, "请绑定客户!");
                            return;
                        }
                        //更新客源中的hid和cid
                        if(customerSource.currentCustomerSource.hid != customerSource.currentHid || customerSource.currentCustomerSource.cid != customerSource.currentCid){
                            com.post(api.customer.updateCustomerOrigin, {"customerOrigin.csid": customerSource.currentCustomerSource.csid, "customerOrigin.hid": customerSource.currentHid, "customerOrigin.cid": customerSource.currentCid,  "customerOrigin.houseNumber": createHouseNumber()}, function(res){}, null, false);
                        }

                        var approvalShowParams = [
                            {"name":"楼盘信息","value": customerSource.currentVillageName + " " + createHouseNumber()},
                            {"name":"客户姓名","value": customerSource.items.name.val()},
                            {"name":"客户电话","value": customerSource.items.phone.val()},
                            {"name":"新设计师","value": customerSource.currentCustomerSource.designer.userName},
                            {"name":"新业务员","value": customerSource.currentCustomerSource.belonger.userName}
                        ];

                        com.post(api.approval.submitApprovalForCustomerOriginTDecoration,
                            {
                                "forms": JSON.stringify(approvalShowParams),
                                "code" : "PROC-FFYJ18LV-JLD1B6W443T9FANLI17V2-0NYO7WPJ-81",
                                "approver" : customerSource.checkUser.join(','),
                                "approvalCustomerOriginTDecoration.csid" : customerSource.currentCustomerSource.csid,
                                "approvalCustomerOriginTDecoration.houseType": customerSource.items.houseType.val(),
                                "approvalCustomerOriginTDecoration.salesmanType": customerSource.items.salesmanType.val(),
                                "decoration.type": customerSource.items.orderType.val(),
                                "approvalCustomerOriginTDecoration.resourceType": customerSource.items.resourceType.val()
                                //"comment": customerSource.items.approveComment.val()
                            }, function (res) {
                                if(res.errorCode == 0){
                                    com.showAlert(com.info, "操作成功");
                                    com.clearValidator();
                                    searcher.doSearch();
                                    com.focusPage("#sustomersource").modal("hide");
                                }else{
                                    com.showAlert(com.error, "提交失败");
                                }
                            });
                    } else {
                        com.showAlert(com.warning, "设计师不匹配, 不能提交审批!");
                    }
                }
            });
        }
    }

    //编辑设计师
    function  updateDesigner(){
        if (com.validate("updateDesigner")) {
            return;
        }

        var options = {
            "customerOrigin.csid": customerSource.currentCustomerSource.csid,
            "customerOrigin.designer.userId": customerSource.items.designer.val()
        };

        com.post(api.customer.updateCustomerOrigin, options, function (res) {
            searcher.doSearch();
            com.showAlert(com.info, '修改成功');
            com.focusPage("#updateDesigner").modal("hide");
        });
    }

    function release(csid) {
        var btn = $(this);
        var span = btn.find('span');
        btn.find('i').remove();
        var loading = $('<i></i>').addClass('icon-spinner icon-spin white bigger-125');
        span.prepend(loading);
        var message = "<p>确定要释放该客源吗?</p>";
        bootbox.confirm(message, function (result) {
            if (result) {
                var options = {
                    "customerOrigin.csid": csid
                };
                com.post(api.customer.freeCustomerOrigin, options, function (res) {
                    searcher.doSearch();
                    com.showAlert(com.info, '释放成功');
                });
            } else {
                btn.find('i').remove();
                var prepared = $('<i></i>').addClass('icon-ok bigger-110');
                span.prepend(prepared);
            }
        });
    }

    function record(csid) {
        var $customerRecord = com.focusPage('#customerRecord');
        $customerRecord.attr({'data-csid': csid});
        layer.open({
            type: 1,
            title: '记录内容',
            content: $customerRecord,
            area: [( $(window).width() * 0.7 < 1000 ? $(window).width() * 0.7 : 1000 ) + "px", ( $(window).height() * 0.84 < 620 ? $(window).height() * 0.84 : 620 ) + "px"],
            maxmin: false,
            zIndex: 9000,
            btn: ['取消'],
            success: function (index, layero) {
                $customerRecord.load("views/customer/customerRecord.html");
            },
            end: function () {
                $customerRecord.attr('data-csid', null);
            }
        });
    }

    //信息是否显示
    function isOtherCustomerSource(isFlag){
        if(isFlag){
            //审批
            com.focusPage("#houseTypeGroup").removeAttr("style");
            com.focusPage("#salesmanTypeGroup").removeAttr("style");
            com.focusPage("#orderTypeGroup").removeAttr("style");
            com.focusPage("#resourceTypeGroup").removeAttr("style");
            com.focusPage("#approveManGroup").removeAttr("style");
            com.focusPage("#checkApproveManGroup").removeAttr("style");
            com.focusPage("#approveCommentGroup").removeAttr("style");
            com.focusPage("#houseNumberGroupTwo").removeAttr("style");
            com.focusPage("#bindHouse").removeAttr("style");
            com.focusPage("#bindCustomer").removeAttr("style");

            com.focusPage("#purposeGroup").css("display", "none");
            com.focusPage("#intentionGroup").css("display", "none");
            com.focusPage("#priceGroup").css("display", "none");
            com.focusPage("#gradeGroup").css("display", "none");
            com.focusPage("#commentGroup").css("display", "none");
            com.focusPage("#buildAreaGroup").css("display", "none");
            com.focusPage("#genderGroup").css("display", "none");
            com.focusPage("#houseNumberGroup").css("display", "none");

            com.focusPage("#houseNumber").attr("disabled", "disabled");
            com.focusPage("#name").attr("disabled", "disabled");
            com.focusPage("#phone").attr("disabled", "disabled");

            com.focusPage("#villageNo").prop("disabled", true);
            com.focusPage("#villageNo").parent().find(".chosen-container").addClass("chosen-disabled");
        }else{
            //更新
            com.focusPage("#houseTypeGroup").css("display", "none");
            com.focusPage("#salesmanTypeGroup").css("display", "none");
            com.focusPage("#orderTypeGroup").css("display", "none");
            com.focusPage("#resourceTypeGroup").css("display", "none");
            com.focusPage("#approveManGroup").css("display", "none");
            com.focusPage("#checkApproveManGroup").css("display", "none");
            com.focusPage("#approveCommentGroup").css("display", "none");
            com.focusPage("#houseNumberGroupTwo").css("display", "none");
            com.focusPage("#bindHouse").css("display", "none");
            com.focusPage("#bindCustomer").css("display", "none");

            com.focusPage("#purposeGroup").removeAttr("style");
            com.focusPage("#intentionGroup").removeAttr("style");
            com.focusPage("#priceGroup").removeAttr("style");
            com.focusPage("#gradeGroup").removeAttr("style");
            com.focusPage("#commentGroup").removeAttr("style");
            com.focusPage("#buildAreaGroup").removeAttr("style");
            com.focusPage("#genderGroup").removeAttr("style");
            com.focusPage("#houseNumberGroup").removeAttr("style");

            com.focusPage("#houseNumber").removeAttr("disabled");
            com.focusPage("#name").removeAttr("disabled");
            com.focusPage("#phone").removeAttr("disabled");

            com.focusPage("#villageNo").prop("disabled", false);
            com.focusPage("#villageNo").parent().find(".chosen-container").removeClass("chosen-disabled");
        }
    }

    function initqueryApprovalUserForCheckbox (id, type, checkId) {
        var $approvalDiv = com.focusPage('#' + id);
        var $checkApprovalDiv = com.focusPage('#' + checkId);

        $approvalDiv.empty();
        $checkApprovalDiv.empty();

        com.post(api.approval.queryApproverByType, {"approver.type": type}, function (res) {
            $.each(res.approvalUsers, function (i, v) {
                var $approvaler = $('<label></label>');
                var $div = $('<div></div>').addClass("radio no-padding").attr("style", "margin-bottom:10px");
                var $input = $('<input>').attr({
                    "type": "checkBox",
                    "name": "form-field-radio",
                    "class": "ace",
                    "id": v.userBase.uid,
                    "userId": v.userBase.userId,
                    "userName":  v.userBase.userName
                });
                var $span = $('<span></span>').addClass('lbl').html($('<label></label>').attr('style', 'display:inline-block;width:47px;text-align-last:justify;margin-left:10px;padding:0px').text(v.userBase.currentName));
                var $comment = $('<span></span>').addClass("lbl").text(v.comment == null ? " " : v.comment).attr("style", "margin-left:15px");
                $input.appendTo($approvaler);
                $span.appendTo($approvaler);
                $comment.appendTo($approvaler);
                $approvaler.appendTo($div);
                $div.appendTo($approvalDiv);

                $input.on('change',function(){
                    if($input.prop('checked')){
                        var li = $('<li style="width: 50%; float: left; padding-bottom: 10px; list-style-type:none;" data-userId="'+v.userBase.userId+'">'+v.userBase.currentName+'</li>');
                        $checkApprovalDiv.append(li);
                        customerSource.checkUser.push(v.userBase.userId)
                    }else{
                        var li = $('li[data-userId="'+v.userBase.userId+'"]');
                        li.remove();
                        customerSource.checkUser.splice(customerSource.checkUser.indexOf(v.userBase.userId),1);
                    }
                });
            });
        });
    }

    function createHouseNumber(){
        var rulenum = [
            customerSource.items.built.val().trim().toUpperCase(), customerSource.items.builtrule.val(),
            customerSource.items.unit.val().trim().toUpperCase(), customerSource.items.unitrule .val(),
            customerSource.items.floor.val().trim().toUpperCase(), customerSource.items.floorrule.val(),
            customerSource.items.door.val().trim().toUpperCase(), customerSource.items.doorrule.val()
        ];

        return houseUtils.creatHouseNumber(rulenum);
    }

    //楼盘号改变的时候清空全局中的currentHid的值
    customerSource.items.built.on("change", function(){
        customerSource.currentHid = null;
    });

    customerSource.items.builtrule.on("change", function(){
        customerSource.currentHid = null;
    });

    customerSource.items.unit.on("change", function(){
        customerSource.currentHid = null;
    });

    customerSource.items.unitrule.on("change", function(){
        customerSource.currentHid = null;
    });

    customerSource.items.floor.on("change", function(){
        customerSource.currentHid = null;
    });

    customerSource.items.floorrule.on("change", function(){
        customerSource.currentHid = null;
    });

    customerSource.items.door.on("change", function(){
        customerSource.currentHid = null;
    });

    customerSource.items.doorrule.on("change", function(){
        customerSource.currentHid = null;
    });

    //绑定房产
    com.focusPage("#bindHouse").click(function(){
        if(com.validate()){
            return;
        }
        var houseOption = {
            "house.village.no" : customerSource.items.villageNo.val(),
            "house.houseNumber" : createHouseNumber(),
            "house.built" : customerSource.items.built.val(),
            "house.unit" : customerSource.items.unit.val(),
            "house.floor" : customerSource.items.floor.val(),
            "house.door" : customerSource.items.door.val(),
            "house.buildArea" : customerSource.items.buildArea.val()
        };

        com.post(api.data.existHouse, houseOption, function(res){
            customerSource.currentHid = res.house.hid;
            com.showAlert(com.info, "绑定成功!")
        })
    });

    //绑定客户
    com.focusPage("#bindCustomer").click(function(){
        if(com.validate()){
            return;
        }
        var customerOption = {
            "customer.name" : customerSource.items.name.val(),
            "customer.phone" : customerSource.items.phone.val(),
            "customer.gender": com.genderType[customerSource.items.gender.prop("checked")],
            "customer.relationshipType" : "普通客户",
            "customer.qq" :  "",
            "customer.wechat" :  "",
            "customer.email" :  "",
            "customer.address" :  ""
        };

        com.post(api.data.existCustomer, customerOption, function(res){
            customerSource.currentCid = res.customer.cid;
            com.showAlert(com.info, "绑定成功!")
        })
    });
});